package com.iceland.server.server.cmd.strategy;

import com.iceland.common.message.CmdMessage;
import com.iceland.common.message.MessageType;
import com.iceland.common.strategy.CmdStrategy;
import com.iceland.common.util.AttributeKeyUtils;
import com.iceland.common.util.ChannelContext;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MarkerFactory;

import java.util.concurrent.atomic.AtomicLong;


/**
 * 转发流量
 */
@Slf4j
public class ForwardStrategy implements CmdStrategy {
    @Override
    public void doStrategy(ChannelHandlerContext ctx, CmdMessage m) {
        //获取要转发的目标请求通道
        ChannelContext channelContext = AttributeKeyUtils.getChannelContext(ctx.channel());
        Channel bindChannel = channelContext.getBindChannel();
        if(bindChannel==null){
           log.error("没有转发目标");
            return;
        }
        //发送数据
        ByteBuf data =m.getData();
        int r=data.readableBytes();


        bindChannel.writeAndFlush(data);
        log.debug(MarkerFactory.getMarker(this.getClass().getTypeName()),"转发来自真实服务端的流量{}字节：CMD服务端{}接收到消息，通过代理服务端{}转发消息至真实客户端{}",r,ctx.channel().localAddress(),bindChannel.localAddress(),bindChannel.remoteAddress());

    }

    @Override
    public int getType() {
        return MessageType.DATA_EXCHANGE.getType();
    }
}
